#include "batteryset.h"
#include "ui_batteryset.h"
#include <QDebug>

BatterySet::BatterySet(int curIndex, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::BatterySet)
{
    ui->setupUi(this);

    curBat = curIndex;

    batInfo = new BattryInfo(curBat, this);
    BatInfo.append(batInfo);

    connect(this, &BatterySet::send_info, batInfo, &BattryInfo::rec_BatInfo, Qt::QueuedConnection);

    ui->tabWidget->addTab(batInfo, QString("%1号电池组").arg(curBat+1));

    ui->tabWidget->setCurrentIndex(0);

    ui->pushButton->setText(QString("停止更新\n设备信息"));
    ui->pushButton_2->setEnabled(false);
}

BatterySet::~BatterySet()
{
    delete ui;
}

void BatterySet::com_rec(QString data_src)
{
    QStringList cmd = data_src.split(",");
    QString canID = cmd.at(3);
    canID = canID.split("=").at(1);
    QString VoID = "1235" + ToStr(curBat, 16, 2);
    QString TempID = "1236" + ToStr(curBat, 16, 2);
    if(canID.indexOf(VoID) != -1 || canID.indexOf(TempID) != -1)
    {
        QString orgData = cmd.at(4);
        orgData = orgData.mid(4, 16);

        qDebug() << "CAN ID:" << canID;
        qDebug() << "data:" << orgData;
        emit send_info(canID, orgData);
    }
}

void BatterySet::on_pushButton_clicked()
{
    if(!ui->pushButton_2->isEnabled())
    {
        ui->pushButton->setText(QString("自动更新\n设备信息"));
        ui->pushButton_2->setEnabled(true);
    }else{
        ui->pushButton->setText(QString("停止更新\n设备信息"));
        ui->pushButton_2->setEnabled(false);
    }
}

void BatterySet::on_pushButton_3_clicked()
{
    disconnect(this, &BatterySet::send_info, batInfo, &BattryInfo::rec_BatInfo);
    emit exit_set();
}

QString BatterySet::ToStr(int number, int base, int size)
{
    return QString("%1").arg(number, size, base, QChar('0'));
}

void BatterySet::on_pushButton_2_clicked()
{
    QByteArray sendBa;

    quint8 intBa[batInfo->batNum];
    for(int i=0; i < batInfo->batNum; i++)
    {
        intBa[i] = batInfo->comBo[i]->currentIndex();
    }

    QByteArray sendID = "@3,CAN,n=8:,ID=1300";
    sendBa.append(sendID);
    sendBa.append(ToStr(curBat*16, 16, 4));
    sendBa.append(",");

    for(int i=0; i < batInfo->batNum; i++)
    {
        sendBa.append(QByteArray::number(intBa[i]));
    }
    sendBa.append("#");

//    sendBa.clear();
//    sendBa.append("@addr,CAN#");

    emit SendSet(sendBa);
    //qDebug() << sendBa;
}

